package com.mxm.mirai.tools;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mxm.mirai.config.MXM_config;
import io.swagger.models.auth.In;
import net.dreamlu.mica.http.HttpRequest;
import net.dreamlu.mica.http.LogLevel;
import net.mamoe.mirai.Bot;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.imageio.ImageIO;
import javax.mail.internet.MimeMessage;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BotTools {
    private static JavaMailSenderImpl javaMailSender;
    private Random random = new Random();
    public String ping(String url_ip) {
        // Java调用 dos命令
        String shell = "ping"+url_ip.replace("-","");
        return cmd(shell);
    }
    public static String cmd(String shell) {
        // Java调用 dos命令
        StringBuffer text = new StringBuffer();
        try {
            Process process = Runtime.getRuntime().exec(shell);
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,"GBK");
            BufferedReader br = new BufferedReader(isr);
            String content = br.readLine();
            while (content != null) {
                text.append("\n"+content);
                content = br.readLine();
            }
            return text.toString();
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    /**
     *  读取jar包中的资源文件
     * @param fileName 文件名
     * @return 文件内容
     * @throws IOException 读取错误
     */
    public String readJarFile(String fileName){
        try {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(BotTools.class.getClassLoader().getResourceAsStream(fileName)));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        return buffer.toString();
        }catch (Exception e){
            return e.getMessage();
        }
    }
    /**
     * 读取jar包中的资源文件
     * @param fileName
     * @return
     * @throws IOException
     */
    public InputStream readJarFileB(String fileName) throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(BotTools.class.getClassLoader().getResourceAsStream(fileName)));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null)
        {
            buffer.append(line);
        }
        return new ByteArrayInputStream(buffer.toString().getBytes());
    }
    /**
     * <p>
     *     获取系统本项目路径
     *     linux系统返回:项目名路径+/WEB-INF/classes/
     *     window系统war项目返回:项目名路径+\src\main\resources\
     *     window系统jar项目返回:项目名路径
     * </p>
     * @return
     */
    public static String GetSystemPath(){
        String filePath=null;
        if("/".equals(File.separator)){//判断系统linux否则win系统
            String classPath = MXM_Tools.class.getClassLoader().getResource("/").getPath();
            filePath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
            filePath = filePath.replace("\\", "/");
            filePath = filePath+"/WEB-INF/classes/";
        }else {
            if(new File(System.getProperty("user.dir")+"/src/main").exists()){
                filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\";
            }else {
                filePath = System.getProperty("user.dir")+"\\";
            }
        }
        return filePath;
    }
    /**
     * 打开浏览器访问特定网址
     * @param url
     */
    public static void openURL(String url) {
        String os = System.getProperty("os.name");
        // Linux
        if (os.indexOf("Linux") != -1) {
            try {
                String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++) {
                    if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) {
                        browser = browsers[count];
                    }
                }
                if (browser != null) {
                    Runtime.getRuntime().exec(new String[] { browser, url });
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }
            // Windows
        } else {
            String cmd = "rundll32 url.dll,FileProtocolHandler http://" + url;
            try {
                Runtime.getRuntime().exec(cmd);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 判断字符是否为整数
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        for (int i = 0; i < str.length(); i++){
            //System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
    /**
     * 判断qq号在登录的机器人中是否存在/是否在线
     * @param qq
     * @return
     */
    public static boolean inBotOnline(String qq){
        for (Bot bot:Bot.getBotInstances()) {
            if(String.valueOf(bot.getId()).equals(qq) && bot.isOnline()){
                return true;
            }
        }
        return false;
    }

    /**
     * 卡牌卡片图片生成
     * @param imgio 图片
     * @param title_a 名字
     * @param title_b 标题
     * @return
     */
    public BufferedImage CreateCards(InputStream imgio,String title_a,String title_b){
        try{
//            String ma="D:\\IDEA\\Mirai\\src\\main\\resources\\img\\ma.png";
//            String mb="D:\\IDEA\\Mirai\\src\\main\\resources\\img\\mb.png";
            String ma=GetSystemPath()+"ma.png";
            String mb=GetSystemPath()+"mb.png";
            Integer width = 400,height=610;
            BufferedImage bga = ImageIO.read(new File(ma));
            BufferedImage bgb = ImageIO.read(new File(mb));
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = img.getGraphics();
            BufferedImage acg = ImageIO.read(imgio);
            g.drawImage(bgb.getScaledInstance(width, height, Image.SCALE_DEFAULT), 0, 0, null);
            g.drawImage(acg.getScaledInstance(width, height, Image.SCALE_DEFAULT), 0, 0, null);
            g.drawImage(bga.getScaledInstance(width, height, Image.SCALE_DEFAULT), 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(new Font("Fixedsys", Font.BOLD, 23));
            g.drawString(title_a, width/2-(title_a.length()*20/2), 547);
            g.drawString(title_b, width/2-(title_b.length()*20/2), 585);
            g.dispose();
//            ImageIO.write(img, "png", new File("D:\\IDEA\\Mirai\\src\\main\\resources\\img\\test.png"));
            System.out.println("生成成功！");
            return img;
        }catch (Exception e){
            return null;
        }
    }
    public BufferedImage TextTurnImage(String text){
        String[] texts=null;
        Integer width=0,height=0,index=0,text_x=0,text_y=0;
        Integer lengthA=0,lengthB=0;
        BufferedImage buffImg = null;
        Graphics g=null;
//===============================================
        if(text.indexOf("\n")>0){
            texts = text.split("\n");
            index = texts.length;
            for (int i = 0; i < index; i++) {
                lengthA = getLength(texts[i]);
                if(lengthA>lengthB){
                    lengthB=lengthA;
                }
            }
            width = lengthB*11;
            height = index*22+4;
            // BufferedImage类是具有缓冲区的Image类
            buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
            // 获取Graphics对象,便于对图像进行各种绘制操作
            g = buffImg.getGraphics();
            // 设置背景色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            text_x=2;
            text_y=20;
//        g.setColor(Color.BLACK);
            g.setFont(new Font("Fixedsys", Font.ROMAN_BASELINE, 20));
            for (int i = 0; i < index; i++) {
//            new Color(1, 33, 4);
//            int colorint = random.nextInt(16711680)%(16711680-65280+1) + 65280;
//            int colorint = random.nextInt(16711680)%(16711680-65280+1) + 65280;
//            g.setColor(new Color(colorint));
                g.setColor(getRandColor(10,120));
                g.drawString(texts[i], text_x, text_y);
                text_y+=22;
            }
        }else {
            lengthA = getLength(text);
            width = lengthA*11;
            height = 22+4;
            // BufferedImage类是具有缓冲区的Image类
            buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
            // 获取Graphics对象,便于对图像进行各种绘制操作
            g = buffImg.getGraphics();
            // 设置背景色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            g.setFont(new Font("Fixedsys", Font.ROMAN_BASELINE, 20));
            g.setColor(getRandColor(10,120));
            g.drawString(text, 2, 20);
        }
//===============================================
        g.dispose();
        return buffImg;
    }
    /**
     * 给定范围获得随机颜色
     */
    private Color getRandColor(int fc, int bc) {
        if (fc > 255){
            fc = 255;
        }
        if (bc > 255){
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
    /**
     * 获取字节长度
     * @param s
     * @return
     */
    public static int getLength(String s) {
        int length = 0;
        for (int i = 0; i < s.length(); i++) {
            int ascii = Character.codePointAt(s, i);
            if (ascii >= 0 && ascii <= 255) {
                length++;
            } else {
                length += 2;
            }
        }
        return length;
    }

    /**
     * 访问URL获取File流
     * @param urlPath 请求URL
     * @return
     */
    public static InputStream getURLFile(String urlPath) {
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 50);
            //设置UA
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            return httpURLConnection.getInputStream();
        } catch (Exception e) {
            MXM_config.log.BotLog(null,"图片请求错误:"+urlPath,true);
            return null;
        }
    }
    /**
     * 智能抠图A(有次数限制，质量差，可挂代理）
     * @param url
     * @return
     */
    public String SmartMattingA(String url){
        RequestBody body = new FormBody.Builder().build();
        Gson gson = new Gson();
        Tools_PicupImg json = null;
        try{
            url = "http://restapi.picup.shop/webMatting/mattingByUrl2?url=" + URLEncoder.encode(url,"UTF-8").replace("%3A",":") + "&mattingType=1";
        }catch (UnsupportedEncodingException e){
            url = "http://restapi.picup.shop/webMatting/mattingByUrl2?url=" + url+"&mattingType=1";
        }
        String id = "", html = HttpRequest.post(url)
                    .body(body)
                    .addHeader("Host", "restapi.picup.shop")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Accept", "application/json, text/plain, */*")
                    .addHeader("Origin", "http://www.picup.shop")
                    .addHeader("Referer", "http://www.picup.shop/people.html")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                    .connectTimeout(Duration.ofSeconds(120))
                    .readTimeout(Duration.ofSeconds(120))
                    .execute().asString();
//           System.out.println(html);
//        {"code":4003,"data":null,"msg":"未登录账号已达今日限额，请登录后使用","time":1601987449235}
            json = gson.fromJson(html, Tools_PicupImg.class);
            if(json.getCode()!=0){
                System.out.println("账号已达今日限额");
            }
            id = json.getData().getFileId();
            System.out.println("ID:" + id
                    + " 图高:" + json.getData().getOriginalHeight()
                    + " 图宽:" + json.getData().getOriginalWidth());
            if ("queuing".equals(json.getData().getStatus())) {
                for (int i = 0; i < 10; i++) {
                    html = HttpRequest.get("http://restapi.picup.shop/webMatting/getMattingInfo?fileId=" + id)
                            .addHeader("Host", "restapi.picup.shop")
                            .addHeader("Connection", "keep-alive")
                            .addHeader("Accept", "application/json, text/plain, */*")
                            .addHeader("Origin", "http://www.picup.shop")
                            .addHeader("Referer", "http://www.picup.shop/people.html")
                            .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                            .connectTimeout(Duration.ofSeconds(120))
                            .readTimeout(Duration.ofSeconds(120))
                            .execute().asString();
                    if (html.indexOf("success") != -1) {
                        json = gson.fromJson(html, Tools_PicupImg.class);
                        //System.out.println("内:" + json.getData().getBgRemovedPreview());
                        //return json.getData().getBgRemovedPreview();
                        return json.getData().getBgRemovedPreview();
                    }
                }
            } else {
                //System.out.println("外:" + json.getData().getBgRemovedPreview());
                return json.getData().getBgRemovedPreview();
            }
            return "";
    }
    /**
     * 智能抠图B(有次数限制，质量好，50次免费）
     * @param url
     * @return
     */
    public InputStream SmartMattingB(String url){
        RequestBody body = new FormBody.Builder()
                .add("image_url",url)
                .add("size","auto")
                .build();
        Request request = new Request.Builder()
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .addHeader("X-Api-Key","需要自己提供")
                .url("https://api.remove.bg/v1.0/removebg")
                .post(body)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder().connectTimeout(100, TimeUnit.SECONDS);
        okHttpClient.newBuilder().readTimeout(100, TimeUnit.SECONDS);
        okHttpClient.newBuilder().callTimeout(100,TimeUnit.SECONDS);
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            if (response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                byte[] bytes = new byte[0];
                bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                String str = new String(bytes);
                if(str.indexOf("Could not identify")!=-1){
                    return null;
                }
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 将BufferedImage转换为InputStream
     * @param image
     * @return
     */
    public InputStream bufferedImageToInputStream(BufferedImage image){
//        System.out.println(image);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            System.out.println(e);
        }
        return null;
    }
    /**
     * 短网址
     * @param url 带上http://或https://
     * @return
     */
    public String DwzUrl(String url){
        String html = HttpRequest.get("http://api.brhsm.cn/url.php?url="+url)
                .connectTimeout(Duration.ofSeconds(300))
                .execute().asString();
        return html;
    }
    /**
     * 缩我短网址
     * @param url 带上http://或https://
     * @return
     */
    public String ShortUrl(String url){
        Long time = System.currentTimeMillis();
        String encoderurl = "";
        try {
            encoderurl = URLEncoder.encode(url,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            encoderurl = "http://URLEncoder_error_500.com";
        }
        RequestBody body = new FormBody.Builder()
                    .add("urlStr", encoderurl)
                    .add("domain","suo.im")
                    .add("extDomain","")
                    .add("expireType","3")
                    .add("key","0@null")
                    .add("mark",RunJavaScript(readJarFile(MXM_config.suow_js_path),"binlz",encoderurl,time))
                    .add("random",String.valueOf(time))
                    .add("createPath","suowo.cn")
                    .build();
        String html = HttpRequest.post("https://create.suowo.cn/pageHome/createBySingle.htm")
                .body(body)
                .addHeader("Accept","application/json, text/javascript, */*; q=0.01")
                .addHeader("sec-ch-ua-mobile","?0")
                .addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Origin","https://suowo.cn")
                .addHeader("Sec-Fetch-Site", "same-site")
                .addHeader("Sec-Fetch-Mode","cors")
                .addHeader("Sec-Fetch-Dest","empty")
                .addHeader("Referer","https://suowo.cn/")
                .addHeader("Accept-Language","zh-CN,zh;q=0.9")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(40))
                .execute().asString();
        JsonParser parser=new JsonParser();
        JsonObject object=  (JsonObject) parser.parse(html);
        String data = object.get("data").getAsString();
       return "".equals(data)?"生成短网址失败！":data;
    }

    /**
     * JavaScript脚本运行
     * @param js_path js文件路径
     * @param fun_name 执行方法名
     * @param vode 参数（多参）
     * @return
     */
    public static String RunJavaScript(String js_path,String fun_name,Object... vode){
        //获取脚本引擎对象
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");
        try {
            FileReader fr = new FileReader(js_path);
            engine.eval(fr);
            Invocable invocable = (Invocable) engine;
            Object res = invocable.invokeFunction(fun_name, vode);
            return res.toString();
        }catch (Exception e){
            return e.getMessage();
        }
    }
    /**
     * 腾讯识图文字（有ip限制）
     * @param url
     * @return
     */
    public String getTxOCR(String url){
        StringBuffer buffer = new StringBuffer();
        byte[] img = HttpRequest.get(url).execute().asBytes();
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), img);
        MultipartBody body2 = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", "VailCode.jpg",fileBody)
                .build();
        String html = HttpRequest.post("https://ai.qq.com/cgi-bin/appdemo_generalocr?g_tk=")
                .setHeader("Content-Type", "multipart/form-data;")
                .addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
                .addHeader("Referer","https://ai.qq.com/product/ocr.shtml")
                .addHeader("Accept-Language","zh-CN")
                .body(body2)
                .log(LogLevel.NONE)
                .execute()
                .asString();
        JsonParser parser=new JsonParser();
        JsonObject object=  (JsonObject) parser.parse(html);
        JsonArray asJsonArray = object.get("data").getAsJsonObject().get("item_list").getAsJsonArray();
        for(int i=0;i<asJsonArray.size();i++){
            JsonObject object2 = asJsonArray.get(i).getAsJsonObject();
            buffer.append(object2.get("itemstring").getAsString()+"\n");
        }
        return buffer.toString();
    }

    /**
     * 百度识图文字（次数限制，每日 50000 次免费调用量）
     * @param api GEOg3wPcIu5VyiGKjkzAfOwx
     * @param client_secret DyllfTepUk08WFv4KS0KRnd0XyTjBvZL
     * @param url
     * @return
     */
    public String getBaiDuOCR(String api,String client_secret,String url){
        String access_token="",//access_token的有效期为30天，需要每30天进行定期更换
                html="";
        JSONObject jsonObject=null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            html = HttpRequest.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+api+"&client_secret="+client_secret)
                    .connectTimeout(Duration.ofSeconds(300))
                    .execute().asString();
//            System.out.println(html);
            jsonObject = new JSONObject(html);
            access_token = jsonObject.getString("access_token");
//            System.out.println(access_token);
            RequestBody body = new FormBody.Builder()
                    .add("url",url)
                    .build();
            html = HttpRequest.post("https://aip.baidubce.com/rest/2.0/ocr/v1/webimage?access_token="+access_token)
                    .setHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                    .body(body)
                    .connectTimeout(Duration.ofSeconds(300))
                    .execute()
                    .asString();
            jsonObject = new JSONObject(html);
            JSONArray arr = jsonObject.getJSONArray("words_result");
            for (int i = 0; i < arr.length(); i++) {
                stringBuffer.append(arr.getJSONObject(i).getString("words")+"\n");
            }
//            System.out.println(stringBuffer);
            return stringBuffer.toString();
        } catch (Exception e) {
            return "";
        }
    }
    public void Xsimg(InputStream ewm) {
        JFrame f1=new JFrame("卡牌");
        f1.setBounds(300, 300, 420, 670);
        f1.setVisible(true);
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BufferedImage bgg = null;
        try {
            bgg = ImageIO.read(ewm);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ImageIcon img=new ImageIcon(bgg);
        JLabel bg=new JLabel(img);
        f1.getLayeredPane().add(bg, new Integer(Integer.MIN_VALUE));
        bg.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
        JPanel jp= (JPanel)f1.getContentPane();//强制类型转换
        jp.setOpaque(false);
        jp.setLayout(new FlowLayout());
        jp.add(bg);
    }
    /**
     * UUID去除-
     **/
    public static String UUID_(){
        return UUID.randomUUID().toString().replace("-", "");
    }
    /**
     * 邮件发送
     * @param host 服务器
     * @param username 账号(QQ就是 qq号+@qq.com)
     * @param password 密码(QQ就是 授权码)
     * @param port 端口
     * @param personal 发信人姓名
     * @param mail 收信人邮箱
     * @param title 邮件标题
     * @param text 邮件内容(支持html)
     * @return
     */
    public static Boolean ToMail(String host, String username, String password, Integer port,String personal,String mail,String title,String text){
        javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);//链接服务器
        javaMailSender.setUsername(username);//账号
        javaMailSender.setPassword(password);//授权码
        javaMailSender.setDefaultEncoding("UTF-8");
        if(port!=465){
            if(port == null){
                javaMailSender.setPort(25);//默认使用25端口发送
            }else {
                javaMailSender.setPort(port);
            }
        }else {
            Properties properties =  new Properties();
            //properties.setProperty("mail.debug", "true");//启用调试
            //properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
            //设置通过ssl协议使用465端口发送、使用默认端口（25）时下面三行不需要
            properties.setProperty("mail.smtp.auth", "true");//开启认证
            properties.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            javaMailSender.setJavaMailProperties(properties);
        }
        try {
            MimeMessage message=javaMailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(username,personal);//发
            helper.setTo(mail);//收
            helper.setSubject(title);
            helper.setText(text,true);
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}